package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.commons.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
/**
 * 品牌
 */
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {
    /**
     * 注入中间表的关系
     */
        @Autowired
        private CategoryBrandService categoryBrandService;
    /**
     * TODO: 根据条件分页查询
     * @param page
     * @param rows
     * @param key
     * @return
     */
    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        //分页信息的健壮性处理
         page = Math.min(page, 100);
         rows = Math.max(rows,5);
        Page<Brand> info = new Page<>(page, rows);
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        query().like(isKeyExists,"name",key)
                .or()
                .eq(isKeyExists,"letter",key)
                .page(info);
        List<Brand> brands = info.getRecords();
        return new PageDTO<>(info.getTotal(),info.getPages(),BrandDTO.convertEntityList(brands));
    }

    /**todo：
     * 根据分类id查询品牌
     * @param id
     * @return
     */
    @Override
    public List<BrandDTO> queryBrandByCategory(Integer id) {
        //根据中间表category_id查询品牌brandid集合
        List<Long> brandIds = this.categoryBrandService.query()
                .eq("category_id", id)
                .list()
                .stream()
                .map(CategoryBrand::getBrandId)
                .collect(Collectors.toList());
        //通过品牌id集合查询品牌集合
        return BrandDTO.convertEntityList(listByIds(brandIds));
    }

    /**
     * todo:根据ID删除品牌
     * @param id
     */
    @Override
    @Transactional
    public void deleteBrandById(Integer id) {
        if(removeById(id)){
            deleteCategoryBarand(id);
        }
    }
    //抽取共同方法，删除中间表的关系
    private void deleteCategoryBarand(Integer id) {
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id",id));
    }

    /**todo：
     * 新增品牌
     * @param brandDTO
     */
    @Override
    @Transactional
    public void addbrand(BrandDTO brandDTO) {
        //把brandDTO转换成brand
        Brand brand = brandDTO.toEntity(Brand.class);
        //保存品牌主键回显
        save(brand);
        //获取分类id集合 并 添加中间表记录
        saveCategoryBrand(brandDTO.getCategoryIds(),brand.getId());
    }

    /**todo：抽取共用方法
     * 插入商品类与品牌的中间表数据
     * @param categoryIds
     * @param id
     */
    private void saveCategoryBrand(List<Long> categoryIds, long id) {
        //返回中间表的对象
        List<CategoryBrand> categoryBrands = categoryIds.stream()
                .map(cid -> CategoryBrand.of(cid, id))
                .collect(Collectors.toList());
        //保存中间表,批量插入
        categoryBrandService.saveBatch(categoryBrands);
    }

    /**todo：
     * 修改商品信息
     * @param brandDTO
     */
    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        //修改品牌表数据
        if(updateById(brand)){
            //删除中间表关系
            deleteCategoryBarand((int) brand.getId());
            //重建中间表关系
            saveCategoryBrand(brandDTO.getCategoryIds(),brand.getId());
        }
    }
}
